package com.csxy.systemmanager.filter;

import com.csxy.systemmanager.entity.LoginUser;
import com.csxy.systemmanager.utils.JwtUtil;
import com.csxy.systemmanager.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter implements Filter {
    @Autowired
    private RedisCache redisCache;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取token
        String token = request.getHeader("token");
        //判断token
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,servletResponse);
            return;
        }
        String userId;
        //解析token
        try{
            userId = JwtUtil.getUserIDbyToken(token);
        }catch(Exception e){
            throw new RuntimeException("token不合法");
        }
        //根据uid 取出redis中的用户 （登录的时候添加到redis key为用户id value为登录的用户）
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        //将当前的登录用户存入到security的context中
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,servletResponse);
    }
}
